;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Account.CheckReceive", [])
        .controller("CheckReceiveCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "$timeout", "$filter", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, UserContextService, $timeout, $filter) {
            var btnPermissionCode = {
                    checkExport: window.ActionCode.checkExport,
                    checkReverse: window.ActionCode.checkReverse,
                    checkAdd: window.ActionCode.checkAdd,
                    checkEdit: window.ActionCode.checkEdit,
                    showCostPrice: window.ActionCode.showCostPrice,
                },
                checkType = 0,
                totalReceivePrice = 0;

            $scope.btnPermission = {
                checkExport: true,
                checkReverse: true,
                checkAdd: true,
                checkEdit: true,
                showCostPrice: true
            };

            $scope.activeFlag = [true, false, false, false];
            $scope.sourceFlag = null;

            $scope.markInfo = {
                allChecked: false,
                curRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.tableConfig = {
                fixedWidth: 160,
                fixedWidth: 190,
                scrollWidth: 1100,
                tableCol: [
                    {
                        name: "收款单号",
                        dataField: "checkOrder",
                        width: 160,
                        isShow: true,
                        isFixed: false,
                        type: "click",
                        clickFn: "viewDetail"
                    },
                    {
                        name: "客户编码",
                        dataField: "dealerCode",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "客户名称",
                        dataField: "purchaseOrgName",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "结算方式",
                        dataField: "settleTypeF",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "付款方式",
                        dataField: "payDesc",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "收款金额",
                        dataField: "totalPrice",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "优惠金额",
                        dataField: "discountPrice",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "预收款扣减",
                        dataField: "advancePayPrice",
                        width: 100,
                        isShow: false,
                        isFixed: false,
                        isSap: true
                    },
                    {
                        name: "车辆额度",
                        dataField: "useVehicleQuota",
                        width: 100,
                        isShow: false,
                        isFixed: false,
                        isSap: true
                    },
                    {
                        name: "实际收款金额",
                        dataField: "realPrice",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "退款金额",
                        dataField: "refundAmount",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "经办人",
                        dataField: "operatorName",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "收款时间",
                        dataField: "createDateF",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "是否红冲",
                        dataField: "isReverseF",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "是否开票",
                        dataField: "invoiceStatusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "审核状态",
                        dataField: "auditStatusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "operate",
                        name: "操作",
                        width: 150,
                        isShow: true,
                        isFixed: true
                    }
                ]
            };
            $scope.dataList = [];
            $scope.settleTypeList = [
                {id: 0, name: "按订单结算"},
                {id: 1, name: "按金额结算"}
            ];
            $scope.isReverseList = [
                {id: 0, name: "否"},
                {id: 1, name: "是"}
            ];
            $scope.isInvoiceList = [
                {id: 0, name: "未开票"},
                {id: 1, name: "部分开票"},
                {id: 2, name: "已开票"}
            ];
            $scope.auditStatusList = [
                {id: 0, name: "待审核"},
                {id: 1, name: "审核通过"}
            ];
            // 付款方式
            $scope.payTypeList = [
                {id: 1, name: "现金"},
                {id: 2, name: "差价"},
                {id: 3, name: "承兑"},
                {id: 4, name: "融资"},
                {id: 5, name: "调账"},
                {id: 6, name: "返利"},
                {id: 7, name: "服务费"},
                {id: 8, name: "报告抵扣"},
                {id: 9, name: "易贷"},
                {id: 10, name: "三方转账"},
                {id: 11, name: "电汇"},
                {id: 12, name: "其它"},
            ];
            //开票状态 
            $scope.ticketState = {
                0:"未开票",
                1:"已开票"
            }
            $scope.toolbarConfig = {};
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/check/export"),
                sectionParam: {ids: []},
                allUrl: ybHttp.RequestUrl("device", "/check/exportAll")
            };
            $scope.condition = {checkType: checkType};

            // 收款单据详情页的返回
            $scope.goBack = function () {
                  var index = $scope.sourceFlag || 0;
                  $scope.changeTab(index);
            };

            $scope.changeTab = function (index) {
                angular.forEach($scope.activeFlag, function (activeFlag) {
                    activeFlag = false;
                });
                $scope.activeFlag[index] = true;
                switch (index) {
                    case 0:
                        initData();
                        $scope.sourceFlag = null;
                        $scope.setFixedWidth();
                        getDataList();
                        break;
                    case 1:
                    case 3:
                        $scope.sourceFlag = index;
                        break;
                    default:
                        break;
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {checkType: checkType};
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                    return;
                }
                $timeout(function () {
                    $scope.toolbarConfig["show" + toolbar] = true;
                });
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.selectAll = function () {
                for (var i = 0; i < $scope.dataList.length; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
                getBillIds();
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.selectSingle = function (item) {
                var selectAll = false;
                if (!item.isChecked) {
                    selectAll = false;
                } else {
                    selectAll = checkAll($scope.dataList);
                }
                $scope.markInfo.allChecked = selectAll;
                getBillIds();
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {left: $scope.tableConfig.fixedWidth + "px"}
                };
            };

            $scope.tabFlag = {};
            var tabFlag = {
                0: "新增收款单",
                1: "编辑收款单"
            };

            $scope.addCheck = function () {
                ybWidget.GetTableCol($scope.addTableInfo.tableConfig.tableCol, 'ftIsOutDesc').isShow = true;
                ybWidget.GetTableCol($scope.addTableInfo.tableConfig.tableCol, 'ftCreateName').isShow = true;

                $scope.orderObj.paymentDate = new Date();
                $scope.orderObj.operatorName = $scope.curUser.name

                $scope.saleNos = {};
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[0];
                $scope.changeTab(1);
            };

            $scope.editCheck = function(item) {
                ybWidget.GetTableCol($scope.addTableInfo.tableConfig.tableCol, 'ftIsOutDesc').isShow = false;
                ybWidget.GetTableCol($scope.addTableInfo.tableConfig.tableCol, 'ftCreateName').isShow = false;

                ybHttp.Get('device', '/check/editItem', { id: item.id }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    const data = resp.value || {};
                    $scope.saleNos = {};
                    $scope.tabFlag.type = 1;
                    $scope.tabFlag.name = tabFlag[1];

                    const hInfo = data.headerInfo || {};
                    hInfo.paymentDate = hInfo.paymentDate ? new Date(hInfo.paymentDate) : null;
                    $scope.orderObj = hInfo;

                    const dList = data.detailList || [];
                    angular.forEach(dList, function(item) {
                        item.isChecked = true;
                        item.billSingleF = $filter("orderType")(item.billSingle); // 单据名称
                        item.billDateF = $filter("YbDate")(item.billDate, 'yyyy-MM-dd HH:mm:ss'); // 单据创建时间
                        item.saleBillTypeStr = $filter("BillTypeStatus")(item.saleBillType); // 单据类型

                        item.remainPrice = item.receivePrice; // 应收金额
                        item.receivePrice = ybWidget.Minus(item.totalPrice, item.remainPrice); // 已收金额
                    })
                    $scope.addTableInfo.markInfo.allChecked = true;

                    $scope.addTableInfo.dataList = dList;

                    $scope.changeTab(1);
                });
            };

            $scope.redFlush = function (item) {
                ybWidget.ShowMessage("单据红冲不可恢复，确定红冲？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/check/reverse";
                    var param = {
                        id: item.id
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            function viewDetail(item, isCheckFlag) {
                $scope.isCheckFlag = isCheckFlag
                $scope.tabFlagName = isCheckFlag ? "审核" : "详情"
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    var df = "yyyy-MM-dd HH:mm:ss";
                    angular.forEach(data.detailList, function (item) {
                        item.billSingleF = $filter("orderType")(item.billSingle);
                        item.billDateF = $filter("YbDate")(item.billDate, df);
                        item.ticketStateShow = $scope.ticketState[item.ticketState]
                    });
                    $scope.detailObj = data;
                    $scope.detailTableInfo.dataList = data.detailList;
                    $scope.changeTab(3);
                });
            }

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            function getDataList(curPage) {
                $scope.markInfo.curRow = -1;
                $scope.markInfo.allChecked = false;

                var service = "device",
                    reqUrl = "/check/list",
                    param = {
                        pageSize: $scope.pageInfo.pageSize,
                        pageNum: $scope.pageInfo.curPage,
                        filters: angular.copy($scope.condition)
                    };

                if (!!curPage) {
                    param.pageNum = $scope.pageInfo.curPage = curPage;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var df = "yyyy-MM-dd HH:mm:ss";
                    angular.forEach(resp.value.list, function (item) {
                        item.settleTypeF = $filter("SettleType")(item.settleType);
                        item.createDateF = $filter("YbDate")(item.createDate, df);
                        item.isReverseF = $filter("TrueOrFalse")(item.isReverse);
                        item.invoiceStatusShow = isInvoice(item.invoiceStatus);
                        item.auditStatusShow = $filter("ProgressStatus")(item.auditStatus, "auditStatus");
                        item.isChecked = false;
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }
            function isInvoice(val) {
                if (String(val) === "0") {
                    return "未开票"
                } else if (String(val) === "1") {
                    return "部分开票"
                } else if (String(val) === "2") {
                    return "已开票"
                } 
            };
            function getDetail(item) {
                var param = {
                    id: item.id
                };
                return ybHttp.Get('device', '/check/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp.value;
                });
            }

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            function initData() {
                $scope.markInfo.allChecked = false;
                $scope.markInfo.curRow = -1;
                $scope.condition = {checkType: checkType};
                $scope.dataList = [];

                $scope.orderObj = {settleType: 0};
                $scope.addTableInfo.markInfo.allChecked = false;
                $scope.addTableInfo.markInfo.curRow = -1;
                $scope.addTableInfo.dataList = [];

                $scope.detailObj = {};
                $scope.detailTableInfo.markInfo.curRow = -1;
                $scope.detailTableInfo.dataList = [];
            }

            $scope.go2checkData = function (item) {
                viewDetail(item, true)
            }

            $scope.checkData = function (id) {
                ybHttp.Get('device', '/check/audit', { id: id }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0)
                });
            }

            $scope.printBill = function (item) {
                var id = item.id;
                var billIds = [];
                billIds.push(id);
                var param = {
                    billId: billIds,
                    printType: "CheckReceive"
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            /**
             * ***************************************** 新增 开始 *****************************************
             */
            $scope.orderObj = {settleType: 0};
            $scope.selectDealer = function () {
                var param = {
                    name: "客户",
                    type: "dealer"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.purchaseOrgId = data.dealerOrgId;
                    $scope.orderObj.purchaseOrgName = data.companyName;
                    $scope.orderObj.prePayPrice = data.advancePayPrice;
                    $scope.orderObj.dealerCode = data.dealerCode;
                    getAddTableDataList();
                    clearTotalPrice();
                })
            };
            $scope.selectAgent = function () {
                var param = {
                    name: "代理商",
                    type: "dealer"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.agentId = data.dealerOrgId;
                    $scope.orderObj.agentName = data.companyName;
                })
            };
            $scope.selectOperator = function () {
                var param = {
                    name: "经办人",
                    type: "agent",
                    supplierOrgId: $scope.curOrgId
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.operatorId = data.userId;
                    $scope.orderObj.operatorName = data.name;
                })
            };
            $scope.saveData = function (valid) {
                if (!valid || !Number($scope.orderObj.totalPrice||0)) {
                    $scope.submitted = true;
                    return;
                }

                var service = "device";
                var reqUrl = "/check/add";
                if ($scope.tabFlag.type == 1) {
                    reqUrl = "/check/submit";
                }

                var param = {};
                param.headerInfo = angular.copy($scope.orderObj);
                param.headerInfo.discountPrice = param.headerInfo.discountPrice || 0;
                param.headerInfo.advancePayPrice = param.headerInfo.advancePayPrice || 0;
                param.headerInfo.checkType = checkType;
                param.headerInfo.supplierOrgId = $scope.curOrgId;
                param.headerInfo.supplierOrgName = $scope.curOrg.companyName;
                param.detailList = [];
                angular.forEach($scope.addTableInfo.dataList, function (item) {
                    if (item.isChecked) {
                        param.detailList.push({
                            arapDetailId: item.id || item.arapDetailId,
                            billDate: item.billDate,
                            billNo: item.billNo,
                            billId: item.billId,
                            billSingle: item.billSingle,
                            mainId: item.mainId,
                            oldCheckPrice: item.oldCheckPrice,
                            checkPrice: item.checkPrice,
                            totalPrice: item.totalPrice,
                            receivePrice: item.remainPrice,
                            saleNo: item.saleNo
                        });
                    }
                });

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };
            $scope.totalPriceChange = function () {
                var str = '' + $scope.orderObj.totalPrice;
                // 如果用户正在输入小数点 直接返回 不然输入不了小数
                if (str.lastIndexOf('.') === str.length - 1) return;
                var totalPrice = Number($scope.orderObj.totalPrice) || 0;
                $scope.orderObj.totalPrice = Math.min(totalPrice, totalReceivePrice);
                if ($scope.addTableInfo.dataList.length === 0) {
                    $scope.orderObj.totalPrice = null;
                    ybWidget.ShowToaster('error', '未选择客户或者选择的客户没有收款单据');
                }
                countRealPrice();
                changeTableData();
            };
            $scope.discountPriceChange = function () {
                countRealPrice();
            };
            $scope.settleTypeClick = function () {
                clearTotalPrice();
                $scope.addTableInfo.markInfo.allChecked = false;
                angular.forEach($scope.addTableInfo.dataList, function (item) {
                    item.isChecked = false;
                    item.checkPrice = null;
                });
            };
            $scope.addTableInfo = {
                markInfo: {
                    allChecked: false,
                    curRow: -1
                },
                tableConfig: {
                    scrollWidth: 900,
                    tableCol: [
                        {
                            name: "单据编号",
                            dataField: "billNo",
                            width: 160,
                            isShow: true,
                            type: "click",
                            clickFn: "viewOrderDetail"
                        },
                        {
                            name: "销售订单号",
                            dataField: "saleNo",
                            width: 160,
                            isShow: true,
                        },
                        {
                            name: "单据名称",
                            dataField: "billSingleF",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "单据类型",
                            dataField: "saleBillTypeStr",
                            width: 100,
                            isShow: false,
                            isSap: true
                        },
                        {
                            name: "单据创建时间",
                            dataField: "billDateF",
                            width: 130,
                            isShow: true
                        },
                        {
                            name: "单据总金额",
                            dataField: "totalPrice",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "是否开票",
                            dataField: "ticketStateShow",
                            width: 100,
                            isShow: $scope.isNY
                        },
                        {
                            name: "已收金额",
                            dataField: "receivePrice",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "应收金额",
                            dataField: "remainPrice",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "本次收款金额",
                            dataField: "checkPrice",
                            width: 120,
                            isShow: true,
                            needInput: true
                        },
                        {
                            name: "出库状态",
                            dataField: "ftIsOutDesc",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "申请人",
                            dataField: "ftCreateName",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "采购订单号",
                            dataField: "purchaseRequestOrder",
                            width: 150,
                            isShow: true
                        },
                    ]
                },
                dataList: [],
                selectRow: function (index) {
                    $scope.addTableInfo.markInfo.curRow = index
                },
                
                selectAll: function () {
                    for (var i = 0; i < $scope.addTableInfo.dataList.length; i++) {
                        $scope.addTableInfo.dataList[i].isChecked = $scope.addTableInfo.markInfo.allChecked;
                    }
                    if ($scope.addTableInfo.dataList.length > 0) {
                        countTotalPrice();
                        countRealPrice();
                    }
                },
                selectSingle: function (item) {
                    var selectAll = false;
                    if (!item.isChecked) {
                        selectAll = false;
                    } else {
                        selectAll = checkAll($scope.addTableInfo.dataList);
                    }
                    $scope.addTableInfo.markInfo.allChecked = selectAll;
                    countTotalPrice();
                    countRealPrice();
                },
                tdClick: function (item, fnType) {
                    switch (fnType) {
                        case "viewOrderDetail":
                            viewOrderDetail(item);
                            break;
                        default:
                            break;
                    }
                }
            };

            function changeTableData() {
                var totalPrice = Number($scope.orderObj.totalPrice) || 0;
                angular.forEach($scope.addTableInfo.dataList, function (item) {
                    var receivePrice = Number(item.remainPrice) || 0;
                    if (totalPrice != 0) {
                        item.isChecked = true;
                        item.checkPrice = Math.min(totalPrice, receivePrice);
                        totalPrice = ybWidget.Minus(totalPrice, item.checkPrice);
                    } else {
                        item.isChecked = false;
                        item.checkPrice = null;
                    }
                });
                $scope.addTableInfo.markInfo.allChecked = checkAll($scope.addTableInfo.dataList);
            }
            //xbt
            $scope.saleNos ={};
            $scope.searchSaleNo = function () { 
                getAddTableDataList();        
            }
            function getAddTableDataList() {
                $scope.addTableInfo.markInfo.curRow = -1;
                $scope.addTableInfo.markInfo.allChecked = false;
                totalReceivePrice = 0;

                var service = "device",
                    reqUrl = "/arap/detailList",
                    param = {
                        filters: {
                            orgId: $scope.orderObj.purchaseOrgId,
                            type: 0,
                            isSettle: 0,
                            isAll: 1,
                            saleNo: $scope.saleNos.saleNo
                        }
                    };

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var df = "yyyy-MM-dd HH:mm:ss";
                    angular.forEach(resp.value.list, function (item) {
                        item.billSingleF = $filter("orderType")(item.billSingle);
                        item.billDateF = $filter("YbDate")(item.billDate, df);
                        item.saleBillTypeStr = $filter("BillTypeStatus")(item.saleBillType);
                        totalReceivePrice = ybWidget.Plus(totalReceivePrice, item.remainPrice);
                        item.isChecked = false;
                        item.ticketStateShow = $scope.ticketState[item.ticketState]
                    });
                    $scope.addTableInfo.dataList = resp.value.list;
                });
            }

            function clearTotalPrice() {
                $scope.orderObj.totalPrice = "";
                $scope.orderObj.discountPrice = "";
                $scope.orderObj.realPrice = "";
                $scope.orderObj.advancePayPrice = "";
            }

            function countTotalPrice() {
                var totalPrice = null;
                angular.forEach($scope.addTableInfo.dataList, function (item) {
                    if (item.isChecked) {
                        if (item.checkPrice === null || item.checkPrice === undefined) {
                            item.checkPrice = item.remainPrice;
                        } 
                        totalPrice = ybWidget.Plus(totalPrice, item.checkPrice);
                    } else {
                        item.checkPrice = null;
                    }
                });
                $scope.orderObj.totalPrice = Number(totalPrice||0).toFixed(2);
            }

            // 预收款价格扣减变化
            $scope.prePayPriceChange = function () {
                var prePayPrice = Number($scope.orderObj.prePayPrice) || 0;
                var advancePayPrice = Number($scope.orderObj.advancePayPrice) || 0;
                // 如果预收款扣减大于客户的预收款额度 则取额度的值
                if (advancePayPrice > prePayPrice) {
                    $scope.orderObj.advancePayPrice = prePayPrice;
                }
                countRealPrice();
            };

            function countRealPrice() {
                var totalPrice = Number($scope.orderObj.totalPrice) || 0,
                    discountPrice = Number($scope.orderObj.discountPrice) || 0;
                var advancePayPrice = Number($scope.orderObj.advancePayPrice) || 0;
                if (!!discountPrice && discountPrice > totalPrice) {
                    $scope.orderObj.discountPrice = discountPrice = totalPrice;
                    $scope.orderObj.advancePayPrice = advancePayPrice = 0;
                }
                var restPrice = ybWidget.Minus(totalPrice, discountPrice);
                if (!!advancePayPrice && advancePayPrice > restPrice) {
                    $scope.orderObj.advancePayPrice = advancePayPrice = restPrice;
                }
                var plus = ybWidget.Plus(discountPrice, advancePayPrice);
                $scope.orderObj.realPrice = ybWidget.Minus(totalPrice, plus);
            }
            /**
             * ***************************************** 新增 结束 *****************************************
             */

            /**
             * ***************************************** 详情 开始 *****************************************
             */
            $scope.detailObj = {};
            $scope.detailTableInfo = {
                markInfo: {
                    curRow: -1
                },
                tableConfig: {
                    scrollWidth: 610,
                    tableCol: [
                        {
                            name: "单据编号",
                            dataField: "billNo",
                            width: 160,
                            isShow: true,
                            type: "click",
                            clickFn: "viewOrderDetail"
                        },
                        {
                            name: "单据类型",
                            dataField: "billSingleF",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "单据创建时间",
                            dataField: "billDateF",
                            width: 130,
                            isShow: true
                        },
                        {
                            name: "单据总金额",
                            dataField: "totalPrice",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "应收金额",
                            dataField: "receivePrice",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "本次收款金额",
                            dataField: "checkPrice",
                            width: 120,
                            isShow: true
                        },
                        {
                            name: "是否开票",
                            dataField: "ticketStateShow",
                            width: 120,
                            isShow: $scope.isNY
                        }
                    ]
                },
                dataList: [],
                selectRow: function (index) {
                    $scope.detailTableInfo.markInfo.curRow = index
                },
                tdClick: function (item, fnType) {
                    switch (fnType) {
                        case "viewOrderDetail":
                            viewOrderDetail(item);
                            break;
                        default:
                            break;
                    }
                }
            };
            /**
             * ***************************************** 详情 结束 *****************************************
             */

            /**
             * ***************************************** 单据详情 开始 *****************************************
             */
            $scope.orderDetailObj = {};
            $scope.orderDetailTableInfo = {
                markInfo: {
                    curRow: -1
                },
                tableConfig: {
                    scrollWidth: 1270,
                    tableCol: [
                        {
                            name: "零件编号",
                            dataField: "materialsNo",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "零件中文名",
                            dataField: "materialsDes",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "单位",
                            dataField: "unit",
                            width: 80,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "默认储位",
                            dataField: "stockLocation",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "订单总数",
                            dataField: "amountAfterAdjust",
                            width: 80,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "已发数量",
                            dataField: "sendQty",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "本次发货",
                            dataField: "deliveryQty",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "单价",
                            dataField: "unitPriceAfterAdjust",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "已出库数",
                            dataField: "inventoryOutAmount",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "实际库存",
                            dataField: "enableNum",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "意向占用",
                            dataField: "intentionNum",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "发货占用",
                            dataField: "deliveryNum",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "安全库存",
                            dataField: "logState",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "危险库存",
                            dataField: "logState",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                        }
                    ]
                },
                dataList: []
            };

            $scope.costPriceShow = false;

            // 销售出库详情table配置
            $scope.saleOutTbConfig = {
                scrollWidth: 1270,
                tableCol: [
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialNo",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialDes",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "默认储位",
                        dataField: "defaultStorage",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "单位",
                        dataField: "unit",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "订单总数",
                        dataField: "totalOrderQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "已发数量",
                        dataField: "issuedQty",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "本次发货",
                        dataField: "thisShipQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "实际出库数量",
                        dataField: "outboundQty",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "单价",
                        dataField: "singlePrice",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        isInput: false
                    },
                    {
                        type: "",
                        name: "实际库存",
                        dataField: "realStockQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "意向占用",
                        dataField: "intentOccupation",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "发货占用",
                        dataField: "shipOccupation",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "安全库存",
                        dataField: "safetyStock",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "库存上线",
                        dataField: "onlineStock",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "cost",
                        name: "成本单价",
                        dataField: "costPrice",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        isInput: false
                    },
                    {
                        type: "cost",
                        name: "成本小计",
                        dataField: "costSubtotal",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        isInput: false
                    },
                ]
            };

            function viewOrderDetail(item) {
                switch (item.billSingle) {
                    case "XGFT":
                        $scope.orderDetailObj = {};
                        $scope.orderDetailTableInfo.dataList = [];
                        getXGFTOrderDetail(item.billId).then(function (data) {
                            if (!data) {
                                return;
                            }
                            $scope.orderDetailObj = data.headerInfo;
                            $scope.orderDetailTableInfo.dataList = data.materialList;
                            $scope.changeTab(2);
                        });
                        break;
                    case "XSCK":
                        getXSCKOrderDetail(item.billId).then(function (data) {
                            if (!data) {
                                return;
                            }
                            $scope.saleOutDetailInfo = data;
                            $scope.changeTab(4);
                        });
                        break;
                    default:
                        break;
                }

            }

            // 获取发货通知单详情
            function getXGFTOrderDetail(billId) {
                var service = "device";
                var reqUrl = "/deliveryNote/item";
                var param = {};
                param.id = billId;
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp.value;
                });
            }

            // 获取销售出库详情
            function getXSCKOrderDetail (id) {
                var url = '/salesBillOut/item';
                return ybHttp.Get('device', url, {id: id}).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return false;
                    }
                    res.value.headerInfo.generateDateStr = $filter("YbDate")(res.value.headerInfo.generateDate, 'yyyy-MM-dd HH:mm:ss');
                    res.value.headerInfo.checkStateShow = $filter("ProgressStatus")(res.value.headerInfo.checkState, "checkState");
                    res.value.headerInfo.outboundStatusStr = $filter("ProgressStatus")(res.value.headerInfo.outboundStatus, "outDepot")
                    res.value.headerInfo.outboundDateStr = $filter("YbDate")(res.value.headerInfo.outboundDate, 'yyyy-MM-dd HH:mm:ss');
                    return res.value;
                })
            }
            /**
             * ***************************************** 单据详情 结束 *****************************************
             */



            $scope.showQtyTip = function (item) {
                if (!!item.chpErr) {
                    item.chpErrMsg = true;
                }
            };
            $scope.hideQtyTip = function (item) {
                item.chpErrMsg = false;
            };

            $scope.checkChp = function (item) {
                item.chpErr = false;
                if (item.checkPrice > item.remainPrice) {
                    item.chpErr = true;
                } else {
                    countTotalPrice();
                    countRealPrice();
                }
            };

            (function () {
                $scope.setFixedWidth();
                getDataList(1);
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);